# Copyright (c) 2024, kaepyz@gmail.com and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class TongtoolSettings(Document):
	def validate(self):
		"""验证配置参数"""
		if self.sync_days_back and self.sync_days_back < 1:
			frappe.throw("同步回溯天数必须大于0")
		
		if self.max_retry_attempts and self.max_retry_attempts < 1:
			frappe.throw("最大重试次数必须大于0")
		
		if self.cache_ttl_minutes and self.cache_ttl_minutes < 1:
			frappe.throw("缓存过期时间必须大于0分钟")
		
		if self.api_rate_limit and self.api_rate_limit < 1:
			frappe.throw("API频率限制必须大于0")
		
		if self.notification_email:
			import re
			email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
			if not re.match(email_pattern, self.notification_email):
				frappe.throw("请输入有效的邮箱地址")

	def on_update(self):
		"""配置更新后的处理"""
		# 清除现有缓存
		frappe.cache().delete_keys("tongtool_*")
		
		# 测试API连接（仅在有凭证时）
		if self.app_key and self.app_secret and not self.flags.ignore_permissions:
			try:
				self.test_api_connection(show_messages=False)
			except Exception as e:
				# 记录错误但不阻止保存
				frappe.log_error(f"API测试失败但已保存配置: {str(e)}")
				frappe.msgprint(
					f"配置已保存，但API测试失败: {str(e)}", 
					title="警告", 
					indicator="orange"
				)

	def test_api_connection(self, show_messages=True):
		"""测试API连接"""
		try:
			from tongtool_integration.api.client import TongToolClient
			
			# 获取真实的密码值（ERPNext的Password字段读取时会被掩码）
			app_secret = self.get_password('app_secret')
			
			if not app_secret:
				if show_messages:
					frappe.throw("App Secret未设置或为空")
				return False
			
			# 避免循环依赖，直接传递base_url
			client = TongToolClient(
				self.app_key, 
				app_secret, 
				self.api_base_url or "https://open.tongtool.com/api-service"
			)
			
			if client.authenticate():
				self.merchant_id = client.token_info.get('merchant_id')
				if show_messages:
					frappe.msgprint("API连接测试成功！", title="连接成功", indicator="green")
				return True
			else:
				if show_messages:
					frappe.throw("API连接测试失败，请检查App Key和App Secret")
				return False
				
		except Exception as e:
			frappe.log_error(f"通途API连接测试失败: {str(e)}")
			if show_messages:
				frappe.throw(f"API连接测试失败: {str(e)}")
			return False
	
	@frappe.whitelist()
	def test_connection(self):
		"""手动测试连接（前端按钮调用）"""
		result = self.test_api_connection(show_messages=True)
		if result:
			self.save()
		return result

	@frappe.whitelist()
	def sync_now(self):
		"""手动触发同步"""
		frappe.enqueue(
			'tongtool_integration.sync.order_sync.manual_sync',
			queue='long',
			timeout=1800,  # 30分钟超时
			job_name=f'manual_tongtool_sync_{frappe.session.user}'
		)
		frappe.msgprint("同步任务已启动，请查看后台任务状态", title="同步启动", indicator="blue")
	
	@frappe.whitelist()
	def refresh_all_orders(self):
		"""手动刷新所有订单数据"""
		try:
			from tongtool_integration.sync.order_sync import bulk_refresh_orders
			
			# 刷新所有有问题的订单
			result = bulk_refresh_orders(
				use_queue=True
			)
			
			# 更新最后刷新时间
			self.last_refresh_time = frappe.utils.now()
			self.save()
			
			if result.get('queued'):
				frappe.msgprint(
					f"批量刷新任务已启动，共 {result.get('total', 0)} 个订单",
					title="刷新任务",
					indicator="blue"
				)
			else:
				frappe.msgprint(
					f"刷新完成！共处理 {result.get('total', 0)} 个订单",
					title="刷新完成",
					indicator="green"
				)
			
			return result
			
		except Exception as e:
			frappe.log_error(f"批量刷新失败: {str(e)}")
			frappe.msgprint(f"刷新失败: {str(e)}", title="错误", indicator="red")
			return {'error': str(e)}
